<?php

namespace services\patient;

use common\components\Service;
use common\models\base\Drug;
use common\models\base\DrugConfig;
use common\models\patient\DrugRecord;
use common\models\patient\DrugSurplus;
use common\models\patient\User;
use services\base\DrugConfigService;
use services\base\DrugService;
use services\clinic\TreatmentRoomService;
use Yii;

/**
 * Class DrugRecordService
 * @package services\patient
 */
class DrugRecordService extends Service
{
    /**
     * 统计患者购买+治疗数量
     * @param $patientUserIds
     * @param int $drugId
     * @return array
     */
    public static function getStatisticsList($patientUserIds, int $drugId): array
    {
        $res = DrugRecord::find()->alias('dr')
            ->select([
                'dr.patient_user_id', 'dr.type', 'SUM(dr.operate_num) operate_num'
            ])
            ->innerJoin(DrugConfig::tableName().' dc', 'dc.id = dr.drug_config_id')
            ->where([
                'dr.patient_user_id' => $patientUserIds,
                'dc.drug_id' => $drugId,
            ])
            ->groupBy('dr.patient_user_id,dr.type')
            ->asArray()
            ->all();
        $data = [];
        foreach ($res as $row) {
            $data[$row['patient_user_id']] = $data[$row['patient_user_id']] ?? [
                'buy_num' => 0,
                'treatment_num' => 0,
            ];
            if ($row['type'] == DrugRecord::TYPE_ADD) {
                $data[$row['patient_user_id']]['buy_num'] += $row['operate_num'];
            } elseif ($row['type'] == DrugRecord::TYPE_USE) {
                $data[$row['patient_user_id']]['treatment_num'] += $row['operate_num'];
            } else {
                $data[$row['patient_user_id']]['buy_num'] -= $row['operate_num'];
            }
        }
        return $data;
    }
}